package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList(){
        //一、List实现
        String key = CACHE_SHOP_TYPE_KEY;
        // 从redis查询商铺列表缓存
        List<String> typeListJson = stringRedisTemplate.opsForList().range(key,0,-1);
        // 判断是否存在
        if(CollUtil.isNotEmpty(typeListJson)){
            // 存在，直接返回
            // 2. 存在，直接返回
            List<ShopType> typeList = typeListJson.stream()
                    .map(json -> JSONUtil.toBean(json, ShopType.class))
                    .toList();
            return Result.ok(typeList);
        }
        // 3. 不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList == null || typeList.isEmpty()) {
            return Result.fail("商铺类型不存在");
        }
        // 4. 写入Redis缓存
        List<String> typeListJsonToCache = typeList.stream()
                .map(JSONUtil::toJsonStr)
                .toList();
        stringRedisTemplate.opsForList().rightPushAll(key, typeListJsonToCache);
        return Result.ok(typeList);

/*        //二、String实现
        String key = CACHE_SHOP_TYPE_KEY;
        //从redis中查询类型缓存
        String typeJson = stringRedisTemplate.opsForValue().get(key);
        //如果缓存不为空，直接返回
        if (StrUtil.isNotBlank(typeJson)) {
            List<ShopType> shopTypeList = JSONUtil.toList(typeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //为空，查询
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if (shopTypeList == null || shopTypeList.isEmpty()) {
            return Result.fail("商铺类型不存在");
        }
        //将数据库信息保存到缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList));
        return Result.ok(shopTypeList);*/

    }
}
